﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.WebAPI.Tools;
using Microsoft.EntityFrameworkCore;
using NetTaste;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    public class TPutawayOrderRepository : BaseRepository<TPutawayOrder>, ITPutawayOrderRepository
    {
        private readonly IBarCodeRuleRepository _BarCodeRuleRepositoy;
        public TPutawayOrderRepository(DFGK_DB context, IMapper mapper, IBarCodeRuleRepository barCodeRuleRepositoy) : base(context, mapper)
        {
            _BarCodeRuleRepositoy = barCodeRuleRepositoy;
        }

        /// <summary>
        /// 查询任务管理信息
        /// </summary>
        /// <param name="code">任务单号</param>
        /// <returns></returns>
        public TPutawayOrder Getputawayorder(Expression<Func<TPutawayOrder, bool>> where)
        {
            return Context.TPutawayOrders.Where(where).FirstOrDefault();

        }
        /// <summary>
        /// 修改任务状态
        /// </summary>
        /// <returns></returns>
        public bool UpdatePutawayorder(TPutawayOrder order)
        {
            var con = Context.TPutawayOrders.Update(order);
            var invobjlist = Context.TInventories.Where(x => x.PalletBarcode == order.PalletBarcode);
            if (invobjlist.Any())
            {
                foreach (var item in invobjlist)
                {
                    item.IsLock = false;
                    item.Status = 1;
                }          
            }
            var tpallobj = Context.TPallets.FirstOrDefault(x => x.PalletBarcode == order.PalletBarcode);
            if (tpallobj == null)
            {
                return false;
            }
            var tcellobj = Context.TCells.FirstOrDefault(x => x.Code == order.LocationCode);
            if (tpallobj != null) 
            {
                tpallobj.LocationName = tcellobj.Name;
                tpallobj.LocationCode = tcellobj.Code;
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 出库单查询
        /// </summary>
        /// <param name="RelatedOrderDetailId"></param>
        /// <returns></returns>
        public TShippingOrderDetail GetShippingLock(int? RelatedOrderDetailId)
        {
            var shipp = Context.TShippingOrderDetails.Where(x => x.Id == RelatedOrderDetailId).FirstOrDefault();
            return shipp;
        }

        /// <summary>
        /// 托盘物料信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public List<PalletMsg> GetPalletmsg(int ids, out string message)
        {
            message = "";
            List<PalletMsg> pallets = new List<PalletMsg>();
            //查询出库单明细
            var detail = Context.TShippingLockCells.Where(x => x.OrderDetailId == ids).FirstOrDefault();
            if (detail == null)
            {
                message = "未查询到出库单明细信息";
                return pallets;
            }
            //根据库存id查找库存信息
            var inven = Context.TInventories.Where(x => x.Id == Convert.ToInt32(detail.InventoryId)).FirstOrDefault();
            if (inven == null)
            {
                message = "未查询到库存信息";
                return pallets;
            }
            PalletMsg pallst = new PalletMsg();
            pallst.palletcode = inven.PalletBarcode;
            pallst.materialcode = inven.MaterialCode;
            pallst.materialname = inven.MaterialName;
            pallst.materialqulitity = inven.AvailableQty.ToString();
            pallets.Add(pallst);
            if (inven.Remark != null)
            {
                var code = inven.Remark.Split(",");
                var num = inven.DictReceiving.Split(",");

                for (int i = 0; i < code.Count(); i++)
                {
                    PalletMsg pall = new PalletMsg();
                    pall.palletcode = code[i];
                    pall.materialcode = inven.MaterialCode;
                    pall.materialname = inven.MaterialName;
                    pall.materialqulitity = num[i];
                    pallets.Add(pall);
                }
            }

            return pallets;
        }

        /// <summary>
        /// 入库
        /// </summary>
        /// <param name="instruct"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool ExecInstructFinished(TPutawayOrder putwarorder, out string errorMsg)
        {
            errorMsg = "";
            //越飞
            var instructlist = Context.TInstructs.Where(x => x.PalletBarcode == putwarorder.PalletBarcode && x.Status == 2 && x.InstructType == 1).ToList();
            if (!instructlist.Any())
            {
                errorMsg = "未查询到指令！";
                return false;
            }
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    foreach (var instruct in instructlist)
                    {
                        if (string.IsNullOrEmpty(instruct.PalletBarcode))
                        {
                            errorMsg = "参数错误";
                            return false;
                        }
                        var orderDetail = Context.TReceivingOrderDetails.Find(instruct.RelatedOrderId);
                        if (orderDetail == null)
                        {
                            errorMsg = "入库单明细不存在";
                            return false;
                        }
                        var inventory = Context.TInventory.FirstOrDefault(x => x.PalletBarcode == instruct.PalletBarcode && x.IsLock == true);
                        if (inventory == null)
                        {
                            errorMsg = "库存数据不存在";
                            return false;
                        }
                        List<TInventoryDetail> inventoryDetailList = Context.TInventoryDetails.Where(x => x.InventoryId == inventory.Id).ToList();
                        if (inventoryDetailList == null || inventoryDetailList.Count == 0)
                        {
                            errorMsg = "库存明细数据不存在";
                            return false;
                        }
                        TCell? cell = Context.TCells.FirstOrDefault(x => x.Code == instruct.ExpectedToLocation);
                        if (cell == null)
                        {
                            errorMsg = "仓位数据不存在";
                            return false;
                        }
                        DateTime? now = DateTime.Now;
                        bool result = false;
                        #region 事务处理
                        instruct.Status = 4;
                        instruct.EndTime = DateTime.Now;
                        Context.TInstructs.Update(instruct);
                        result = Context.SaveChanges() > 0;
                        if (!result)
                        {
                            tran.Rollback();
                            errorMsg = "指令插入失败";
                            return false;
                        }
                        var inventory1 = Context.TInventories.Find(inventory.Id);
                        if (inventory1 == null)
                        {
                            errorMsg = "找不到该库存";
                            tran.Rollback();
                            return false;
                        }
                        inventory1.Status = 1;
                        inventory1.AllocateQty = instruct.Qty;
                        inventory1.InStockDate = now;
                        inventory1.InStockShortDate = Convert.ToInt32(now.Value.ToString("yyyyMMdd"));
                        inventory1.PutawayQty = instruct.Qty;
                        inventory1.IsLock = false;
                        Context.TInventory.Update(inventory1);
                        var count = Context.SaveChanges();
                        if (count <= 0)
                        {
                            errorMsg = "库存状态修改失败";
                            tran.Rollback();
                            return false;
                        }
                        var cell1 = Context.TCells.Find(inventory.LocationId);
                        if (cell1 == null)
                        {
                            errorMsg = "未查询到此仓位";
                            tran.Rollback();
                            return false;
                        }
                        cell1.IsLock = false;
                        cell1.BusinessType = 0;
                        cell1.Status = 1;
                        cell1.FullStatus = 1;
                        cell1.ModifyDate = now;
                        Context.TCells.Update(cell1);
                        count = Context.SaveChanges();
                        if (count <= 0)
                        {
                            errorMsg = "仓位状态修改失败";
                            tran.Rollback();
                            return false;
                        }
                        //查询组垛
                        bool isUpdateOrderDetail = true;
                        #region 弃用拆卸
                        //List<string> palletBarcodes = new List<string>();
                        //var stackingStorage = Context.TStackingStorages.FirstOrDefault(x => x.Status == 1 && x.PalletBarcode == inventory.PalletBarcode);
                        ////_Client.Queryable<TStackingStorage>().First(s => s.Status == 1 && s.PalletBarcode == inventory.PalletBarcode);
                        //List<TStackingStorage> stackingStorageModels = Context.TStackingStorages.Where(x => x.Status == 1 && (x.PalletBarcode == stackingStorage.PalletBarcode || x.PalletBarcode == stackingStorage.PalletBarcode)).ToList();
                        ////_Client.Queryable<TStackingStorage>().Where(s => s.Status == 1 && (s.PalletBarcode == stackingStorage.PalletBarcode || s.ParentPalletBarcode == stackingStorage.PalletBarcode)).ToList();
                        //if (stackingStorageModels.Count > 1)
                        //{
                        //    //拆卸
                        //    palletBarcodes = stackingStorageModels.Select(t => t.PalletBarcode).Distinct().ToList();
                        //    count = Context.TInventory.Where(x => x.Status == 1 && x.IsLock == false && palletBarcodes.Contains(x.PalletBarcode)).Count();
                        //    //_Client.Queryable<TInventory>().Where(i => i.Status == 1 && i.IsLock == false && palletBarcodes.Contains(i.PalletBarcode)).Count();
                        //    if (palletBarcodes.Count == count)
                        //    {
                        //        isUpdateOrderDetail = true;
                        //    }
                        //    else
                        //    {
                        //        isUpdateOrderDetail = false;
                        //    }
                        //}
                        #endregion
                        if (isUpdateOrderDetail)
                        {
                            decimal? totalPutawayQTY = instruct.Qty;
                            TReceivingOrderDetail modifyOrderDetail = new TReceivingOrderDetail
                            {
                                ReceivedQty = totalPutawayQTY,
                                InStarDate = orderDetail.InStarDate == null ? now : orderDetail.InStarDate,
                            };
                            if (totalPutawayQTY.GetValueOrDefault() >= orderDetail.Qty.GetValueOrDefault())
                            {
                                modifyOrderDetail.Status = (int)EmBillStatus.Finished;
                            }

                            var receivingOrderDetail = Context.TReceivingOrderDetails.Find(orderDetail.Id);
                            if (receivingOrderDetail == null)
                            {
                                errorMsg = "找不到入库单";
                                tran.Rollback();
                                return false;
                            }
                            receivingOrderDetail.ReceivedQty = modifyOrderDetail.ReceivedQty;
                            receivingOrderDetail.InStarDate = modifyOrderDetail.InStarDate;
                            receivingOrderDetail.Status = modifyOrderDetail.Status;
                            Context.TReceivingOrderDetails.Update(receivingOrderDetail);
                            count = Context.SaveChanges();
                            if (count <= 0)
                            {
                                errorMsg = "订单明细修改失败";
                                tran.Rollback();
                                return false;
                            }
                        }
                        //保存库存日志表
                        //如果是回流入库就不填库存流水
                        if (orderDetail.SourceType == 4)
                        {
                            //数量的修改可以先把库存数量修改为0 然后把需要修改的数据赋到入库单上
                            tran.Commit();
                            return true;
                        }
                        TInventoryLog inventoryLog = new TInventoryLog()
                        {
                            SourceType = 0,
                            SourceSn = orderDetail.OrderSn,
                            WarehouseId = orderDetail.WarehouseId,
                            WarehouseName = orderDetail.WarehouseName,
                            AreaName = inventory.AreaName,
                            AreaId = inventory.AreaId,
                            LocationCode = inventory.LocationCode,
                            PalletBarcode = instruct.PalletBarcode,
                            OwnerId = orderDetail.OwnerId,
                            OwnerName = orderDetail.OwnerName,
                            MaterialId = orderDetail.MaterialId,
                            MaterialCode = orderDetail.MaterialCode,
                            MaterialName = orderDetail.MaterialName,
                            BatchNo = orderDetail.BatchNo,
                            SmallBatchNo = orderDetail.SmallBatchNo,
                            StartQty = 0,
                            ChangeQty = instruct.Qty,
                            EndQty = instruct.Qty,
                            BaseUnitId = orderDetail.UnitId,
                            BaseUnitName = orderDetail.UnitName,
                            CreateDate = DateTime.Now,
                        };
                        Context.TInventoryLogs.Add(inventoryLog);
                        int logId = Context.SaveChanges();
                        //_Client.Insertable<TInventoryLog>(inventoryLog).ExecuteReturnIdentity();
                        if (logId < 0)
                        {
                            errorMsg = "库存日志表保存失败";
                            tran.Rollback();
                            return false;
                        }
                        #endregion
                    }
                    putwarorder.Status = 5;
                    putwarorder.Fifodate = DateTime.Now;
                    Context.TPutawayOrders.Update(putwarorder);
                    bool result2 = Context.SaveChanges() > 0;
                    if (!result2)
                    {
                        errorMsg = "上架单状态修改失败";
                        tran.Rollback();
                        return false;
                    }
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 出库
        /// </summary>
        /// <param name="instruct"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool HandleUnbindOfOutstorageEnd(TPutawayOrder putwarorder, out string message)
        {
            message = "";
            //越飞
            var instructlist = Context.TInstructs.Where(x => x.PalletBarcode == putwarorder.PalletBarcode && x.Status == 2 && x.InstructType == 2).ToList();
            if (!instructlist.Any())
            {
                message = "未查询到指令！";
                return false;
            }
            bool result;
            using (var tran = Context.Database.BeginTransaction())
            {
                foreach (var instruct in instructlist)
                {
                    try
                    {
                        //仓位
                        //var tell = GetInventoryByTCell(instruct.PalletBarcode);
                        var tell = Context.TCells.FirstOrDefault(x => x.Code == instruct.ExpectedToLocation);
                        if (tell == null)
                        {
                            message = "未查询到仓位！";
                            return false;
                        }
                        instruct.Status = 4;
                        instruct.EndTime = DateTime.Now;
                        //出库单id
                        int shippid = Convert.ToInt32(instruct.RelatedOrderId);
                        //拿到库存id
                        int? invid = Context.TShippingLockCells.FirstOrDefault(x => x.OrderDetailId == instruct.RelatedOrderId)?.InventoryId;
                        //拿到入库单id
                        int? treoid = Context.TInventory.Find(invid)?.RelatedOrderDetailId;
                        //拿到组垛id
                        int? stackid = Context.TStackingStorages.FirstOrDefault(x => x.RelatedOrderDetailId == treoid)?.Id;
                        //组垛
                        //TStackingStorage model = this.GetStackingStorageStatus(instruct.PalletBarcode, shippid, 1);
                        TStackingStorage? model = Context.TStackingStorages.FirstOrDefault(x => x.PalletBarcode == instruct.PalletBarcode && x.Status == 1 && x.Id == stackid);
                        if (model == null)
                        {
                            message = "未查询到组垛信息！";
                            tran.Rollback();
                            return false;
                        }
                        model.Qty = model.Qty - instruct.Qty;
                        result = UpdateStackingStorage(model);
                        if (!result)
                        {
                            message = "更新垛条码信息失败";
                            tran.Rollback();
                            return false;
                        }
                        //TInventory inventoryModel = GetInventory(instruct.PalletBarcode);
                        TInventory? inventoryModel = Context.TInventory.Find(invid);
                        if (inventoryModel == null)
                        {
                            message = "未查询到库存信息！";
                            tran.Rollback();
                            return false;
                        }
                        decimal? startQty = inventoryModel.AvailableQty;
                        decimal? changeQty = instruct.Qty;
                        // 库存数量减去需要出库的数量
                        if (inventoryModel.AvailableQty - instruct.Qty == 0)
                        {
                            result = DeleteInventory(inventoryModel.Id);
                            if (!result)
                            {
                                message = "删除库存信息失败";
                                return false;
                            }
                            var pallobj = Context.TPallets.FirstOrDefault(x => x.LocationCode == tell.Code && x.LocationName == tell.Name);
                            if (pallobj != null)
                            {
                                pallobj.LocationName = string.Empty;
                                pallobj.LocationCode = string.Empty;
                            }
                            var invpal = Context.TInventory.FirstOrDefault(x => x.PalletBarcode == instruct.PalletBarcode);
                            if(invpal==null)
                            {
                                tell.FullStatus = 0;
                                tell.IsLock = false;
                                tell.BusinessType = 0;
                                tell.ModifyDate = DateTime.Now;
                                tell.Status = 1;
                                Context.TCells.Update(tell);
                            }                         
                            Context.SaveChanges();
                            // 如果出完库就修改仓位锁定表数据 
                            if (!UpdTShippingLockCell(shippid, instruct.PalletBarcode))
                            {
                                message = "出库明细信息有误！";
                                return false;
                            }
                        }
                        else
                        {
                            // 减去库存数量并修改库存状态
                            if (!GetDwindleNumbers(inventoryModel, instruct.Qty))
                            {
                                message = "修改库存状态失败";
                                return false;
                            }
                            // 如果没有出完库就更新仓位锁定表中的库存数量
                            var lockCell = Context.TShippingLockCells.Where(s => s.OrderDetailId == instruct.RelatedOrderId && s.PalletBarcode == instruct.PalletBarcode).FirstOrDefault();
                            if (lockCell != null)
                            {
                                lockCell.InventoryQty -= instruct.Qty;
                                lockCell.IsPicking = true;
                                Context.TShippingLockCells.Update(lockCell);
                                Context.SaveChanges();
                            }
                        }

                        var shippingOrderDetail = Context.TShippingOrderDetails.Find(shippid);
                        if (shippingOrderDetail == null)
                        {
                            message = "未查询到单号";
                            return false;
                        }
                        var lockList = Context.TShippingLockCells.Where(x => x.OrderDetailId == shippid);
                        if (lockList == null)
                        {
                            message = "未查询到单号" + shippingOrderDetail.OrderSn + "的出库单详情";
                            return false;
                        }

                        if (shippingOrderDetail != null)
                        {
                            shippingOrderDetail.ShippedQty += instruct.Qty;
                            if (shippingOrderDetail.ShippedQty == shippingOrderDetail.Qty)
                            {
                                shippingOrderDetail.Status = 4;
                            }
                            Context.SaveChanges();
                        }
                        else
                        {
                            message = "出库单状态修改失败";
                            return false;
                        }
                        putwarorder.Status = 5;
                        putwarorder.Fifodate = DateTime.Now;
                        //库存流水
                        var inventoryLog = new TInventoryLog
                        {
                            SourceType = 1,
                            SourceSn = shippingOrderDetail.OrderSn,
                            WarehouseId = shippingOrderDetail.WarehouseId,
                            WarehouseName = shippingOrderDetail.WarehouseName,
                            AreaName = shippingOrderDetail.AreaName,
                            LocationCode = inventoryModel.LocationCode,
                            PalletBarcode = inventoryModel.PalletBarcode,
                            OwnerId = shippingOrderDetail.OwnerId,
                            OwnerName = shippingOrderDetail.OwnerName,
                            MaterialId = inventoryModel.MaterialId,
                            MaterialCode = inventoryModel.MaterialCode,
                            MaterialName = inventoryModel.MaterialName,
                            BatchNo = inventoryModel.BatchNo,
                            StartQty = startQty,
                            ChangeQty = changeQty,
                            EndQty = startQty - changeQty, //使用库存数量减去实际出库数量 等于最终数量
                            BaseUnitId = 0,
                            BaseUnitName = inventoryModel.UnitName,
                            Remark = "",
                            CreateDate = DateTime.Now,
                            CreateUserId = shippingOrderDetail.CreateUserId,
                            CreateUser = shippingOrderDetail.CreateUserName,
                            SmallBatchNo = "",

                        };
                        Context.TInventoryLogs.Add(inventoryLog);
                        bool result2 = Context.SaveChanges() > 0;
                        if (!result2)
                        {
                            message = "保存库存流水失败！";
                            return false;
                        }
                    }
                    catch (Exception)
                    {

                        throw;
                    }
                }
                tran.Commit();
                return true;
            }
        }

        #region 出库解绑私有方法
        /// <summary>
        /// 仓位
        /// </summary>
        /// <param name="palletBarcode"></param>
        /// <returns></returns>
        private TCell GetInventoryByTCell(string palletBarcode)
        {
            TInventory inventoryModel = GetInventory(palletBarcode);

            if (inventoryModel == null)
            {
                return null;
            }

            var cell = Context.TCells.Where(x => x.Code == inventoryModel.LocationCode).FirstOrDefault();
            return cell;

        }

        /// <summary>
        /// 根据托盘条码号查询库存表
        /// </summary>
        /// <param name="PalletBarcode"></param>
        /// <returns></returns>
        private TInventory GetInventory(string PalletBarcode)
        {
            var list = Context.TInventories
                .FirstOrDefault(x => x.PalletBarcode == PalletBarcode);

            if (list == null)
            {
                return null;
            }
            return list;
        }

        /// <summary>
        /// 更新仓位信息
        /// </summary>
        /// <param name="tcell"></param>
        /// <returns></returns>
        private bool UpdateCell(TCell tcell)
        {
            try
            {
                if (tcell == null)
                {
                    return false;
                }
                tcell.FullStatus = 0;
                tcell.IsLock = false;
                tcell.BusinessType = 0;
                tcell.ModifyDate = DateTime.Now;
                tcell.Status = 1;

                return true;
            }
            catch
            {
                return false;
            }

        }

        /// <summary>
        /// 获取入库垛信息及状态
        /// </summary>
        /// <param name="PalletBarcode"></param>
        /// <param name="reorderid"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        private TStackingStorage GetStackingStorageStatus(string PalletBarcode, int reorderid, int status)
        {
            var list = Context.TStackingStorages
                .Where(x => x.PalletBarcode == PalletBarcode && x.Status == status)
                .FirstOrDefault();

            return list;
        }

        /// <summary>
        /// 删除库存表数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private bool DeleteInventory(int id)
        {
            try
            {
                var lobj = Context.TInventories.FirstOrDefault(x => x.Id == id);
                if (lobj == null)
                {
                    return false;
                }
                Context.TInventories.Remove(lobj);
                var idobj = Context.TInventoryDetails.FirstOrDefault(x => x.InventoryId == lobj.Id);
                if (idobj != null)
                {
                    Context.TInventoryDetails.Remove(idobj);
                }
                Context.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 修改仓位锁定状态
        /// </summary>
        /// <param name="OrderId"></param>
        /// <returns></returns>
        private bool UpdTShippingLockCell(int OrderId, string palletBarCode)
        {
            try
            {
                var list = Context.TShippingLockCells
               .FirstOrDefault(x => x.OrderDetailId == OrderId && x.PalletBarcode == palletBarCode);
                if (list == null)
                {
                    return false;
                }
                list.IsPicking = true;
                Context.TShippingLockCells.Update(list);
                Context.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }


        }

        /// <summary>
        /// 更新垛主表的状态为失效状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private bool UpdateStackingStorage(TStackingStorage model)
        {
            //var sobj = Context.TStackingStorages
            //    .Find(model.Id);

            if (model == null)
            {
                return false;
            }
            if (model.Qty <= 0)
            {
                //model.Status = 0;
                Context.TStackingStorages.Remove(model);
            }
            else
            {
                model.ModifyDate = DateTime.Now;
            }

            //model.ModifyDate = DateTime.Now;
            return true;
        }

        /// <summary>
        /// 减去库存数量并修改库存状态
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private bool GetDwindleNumbers(TInventory upd, decimal? num)
        {
            if (upd == null)
            {
                return false;
            }
            upd.AvailableQty = upd.AvailableQty - num;
            //upd.Status = 1;
            Context.SaveChanges();

            return true;

        }

        public bool CompleteTransferBinOrders(TPutawayOrder putwarorder, out string message)
        {
            message = string.Empty;
            //越飞
            var instructlist = Context.TInstructs.Where(x => x.PalletBarcode == putwarorder.PalletBarcode && x.Status == 2 && x.InstructType == 3);
            if (!instructlist.Any())
            {
                message = "未查询到指令！";
                return false;
            }
            using (var tran = Context.Database.BeginTransaction())
            {
                foreach (var instruct in instructlist)
                {
                    instruct.Status = 4;
                    instruct.EndTime = DateTime.Now;
                    Context.TInstructs.Update(instruct);
                    var stackobj = Context.TStackingStorages.Find(instruct.StackingStorageId);
                    if (stackobj == null)
                    {
                        message = "组垛信息有误！";
                        tran.Rollback();
                        return false;
                    }
                    stackobj.Status = 1;
                    Context.TStackingStorages.Update(stackobj);
                    var invobj = Context.TInventories.FirstOrDefault(x => x.PalletBarcode == instruct.PalletBarcode && x.Status == 2 && x.IsLock == true);
                    if (invobj == null)
                    {
                        message = "库存中找不到该托盘！";
                        tran.Rollback();
                        return false;
                    }
                    invobj.Status = 1;
                    invobj.IsLock = false;
                    Context.SaveChanges();
                    Context.TInventories.Update(invobj);
                    putwarorder.Status = 5;
                    putwarorder.Fifodate = DateTime.Now;
                    Context.TPutawayOrders.Update(putwarorder);
                    var treivingobj = Context.TReceivingOrderDetails.Find(invobj.RelatedOrderDetailId);
                    if (treivingobj == null)
                    {
                        message = "找不到入库单或已被删除！";
                        tran.Rollback();
                        return false;
                    }
                    var inventoryLog = new TInventoryLog
                    {
                        SourceType = 4,
                        SourceSn = treivingobj.OrderSn,
                        WarehouseId = 2,
                        WarehouseName = "中煤科院仓库",
                        AreaName = "中煤科院库区",
                        LocationCode = invobj.LocationCode,
                        PalletBarcode = instruct.PalletBarcode,
                        OwnerId = 0,
                        OwnerName = "",
                        MaterialId = invobj.MaterialId,
                        MaterialCode = invobj.MaterialCode,
                        MaterialName = invobj.MaterialName,
                        BatchNo = invobj.BatchNo,
                        StartQty = invobj.AvailableQty,
                        ChangeQty = 0,
                        EndQty = invobj.AvailableQty,
                        BaseUnitId = 0,
                        BaseUnitName = invobj.UnitName,
                        Remark = "",
                        CreateDate = DateTime.Now,
                        CreateUserId = invobj.CreateUserId,
                        CreateUser = invobj.CreateUserName,
                        SmallBatchNo = "",
                    };
                    Context.TInventoryLogs.Add(inventoryLog);
                }
                tran.Commit();
                return Context.SaveChanges() > 0;
            }
            
        }
        #endregion

        /// <summary>
        /// 模式查询
        /// </summary>
        /// <returns></returns>
        public TStation GetLinemodel()
        {
            return Context.TStations.Where(x => x.Id == 2).FirstOrDefault();

        }
        /// <summary>
        /// 模式修改
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public bool UpdateStationsLine(string type)
        {
            var station = Context.TStations.Where(x => x.Id == 2).FirstOrDefault();
            station.Remark = type;
            var con = Context.TStations.Update(station);
            return Context.SaveChanges() > 0;

        }
    }
}
